/*
 * @Author: Setsuna
 * @Email: setsuna.xyz@qq.com
 * @FilePath: \src\pages\SystemSettings\StatementOfAccountConfig\EconomicBusinessConfig\components\CalcFormula.tsx
 * @Date: 2022-03-28 15:21:36
 * @LastEditTime: 2022-04-13 11:34:41
 */
import UdSelect from '@/components/UdFormControls/UdSelect'
import { columnRenders, IUdColumn, UdTable } from '@/lib'
import { randomNumber } from '@/utils/methods'
import { useSafeState, useUpdateEffect } from 'ahooks'
import { Button, Select } from 'antd'
import React, { ReactNode } from 'react'
const { OptGroup } = Select
interface IProps {
  memoizedGetSourceCalcType: () => ReactNode
  getFinancialField: (params?) => ReactNode
  memoizedGetHandType: () => void
  onChange: (params) => void
  value: any
}

const CalcFormula = (props: IProps) => {
  const { memoizedGetSourceCalcType, getFinancialField, memoizedGetHandType, value = {}, onChange } = props
  const [tableData, setTableData] = useSafeState<any[]>(value?.letterCalculationTw ?? [])
  const [result, setResult] = useSafeState<any>(value?.result ?? 'DDZE')
  useUpdateEffect(() => {
    setTableData(props.value.letterCalculationTw)
    setResult(props.value.result)
  }, [props.value])

  useUpdateEffect(() => {
    setResult(result)
    onChange({ result, letterCalculationTw: [...tableData] })
  }, [result])

  function triggerChange(params) {
    let { record, index, key, fieldValue, type } = params
    let newTableData = [...tableData]
    if (key === 'result') {
      setResult(fieldValue)
    } else {
      if (type === 'add') {
        let dataItem = {
          vid: randomNumber(7),
          mode: '+',
          calculationTw: 'DDZE',
        }
        newTableData.splice(newTableData.length, 0, dataItem)
      } else if (type === 'delete') {
        newTableData.splice(index, 1)
      } else {
        let newRecord = { ...record, [key]: fieldValue }
        newTableData.splice(index, 1, newRecord)
      }
      setTableData([...newTableData])
      onChange({ result, letterCalculationTw: [...newTableData] })
    }
  }

  const columns: IUdColumn<any>[] = [
    {
      title: '计算方式',
      dataIndex: 'mode',
      align: 'center',
      width: 90,
      render: (text, record, index) => (
        <UdSelect
          options={memoizedGetHandType()}
          showSearch={true}
          optionFilterProp="children"
          value={record.mode + ''}
          onChange={value => {
            triggerChange({ record, index, key: 'mode', fieldValue: value })
          }}
        />
      ),
    },
    {
      title: '计算值',
      dataIndex: 'calculationTw',
      align: 'center',
      minWidth: '160px',
      render: (text, record, index) => (
        <Select
          style={{ width: 200 }}
          optionFilterProp="children"
          value={record.calculationTw}
          onChange={value => {
            triggerChange({ record, index, key: 'calculationTw', fieldValue: value })
          }}
        >
          <OptGroup label="财务字段">{getFinancialField(1)}</OptGroup>
          <OptGroup label="计算条件">{memoizedGetSourceCalcType()}</OptGroup>
        </Select>
      ),
    },
    {
      title: '操作',
      dataIndex: 'hand',
      align: 'center',
      minWidth: '120px',
      render: columnRenders.operate([
        {
          title: '删除',
          action: (text, record, index) => {
            triggerChange({ record, index, type: 'delete' })
          },
        },
      ]),
    },
  ]
  return (
    <>
      <div style={{ marginBottom: 16 }}>
        <Select
          style={{ width: 200 }}
          value={value?.result ?? 'DDZE'}
          onChange={value => {
            triggerChange({ key: 'result', fieldValue: value })
          }}
        >
          <OptGroup label="财务字段">{getFinancialField(1)}</OptGroup>
          <OptGroup label="计算条件">{memoizedGetSourceCalcType()}</OptGroup>
        </Select>
        <Button
          type="primary"
          style={{ marginLeft: '20px' }}
          onClick={() => {
            triggerChange({ type: 'add' })
          }}
        >
          增加计算公式
        </Button>
      </div>
      <UdTable rowKey="vid" columns={columns} dataSource={value?.letterCalculationTw ?? []} pagination={false} />
    </>
  )
}

const CalcFormulaRef = React.forwardRef((props: any, ref: any) => {
  return <CalcFormula {...props} />
})

export default React.memo(CalcFormulaRef)
